package com.gxc.mall.goods.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxc.mall.common.util.RestControllerResult;
import com.gxc.mall.goods.dto.UserEntity;
import com.gxc.mall.goods.feign.UserFeign;
import com.gxc.mall.goods.service.UserService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author GongXincheng
 * @since 2019-09-03 17:53
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserFeign userFeign;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UserService userService;

    @GetMapping("/feign/hello")
    public Object test() {
        return userFeign.hello();
    }

    @GetMapping("/feign/hello2")
    public Object test2() {
        return userFeign.hello2();
    }

    @GetMapping("/feign/hello3")
    public Object test2(@RequestParam("name") String name) {
        return userFeign.hello3(name);
    }

    /**
     * 根据id查询user.
     */
    @GetMapping("/{id}")
    public RestControllerResult<UserEntity> findUserById(@PathVariable Integer id) throws IOException {
//        ResponseEntity<String> entity = restTemplate.getForEntity("http://CLOUD-MALL-SERVICE-USER/user/{1}", String.class, id);
        ResponseEntity<RestControllerResult<UserEntity>> entity = userService.findUserById(id);
        if (entity.getStatusCode().equals(HttpStatus.OK)) {
            return RestControllerResult.success(entity.getBody().getData());
        }
        return RestControllerResult.success(null);
    }

    /**
     * 添加用户.
     */
    @GetMapping("/addUser")
    public RestControllerResult addUser() {
        UserEntity userEntity = new UserEntity();
        userEntity.setAge(23);
        userEntity.setUsername("GXC");
        userEntity.setPassword("123qwe");
        userEntity.setEmail("gxc@163.com");
        userEntity.setLastLoginTime(LocalDateTime.now());
        userEntity.setStatus(1);
        Object result = restTemplate.postForObject("http://CLOUD-MALL-SERVICE-USER/user", userEntity, Object.class);
        return RestControllerResult.success(result);
    }
}
